﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TRACv2.UI.Facade;

//Author: Morgan William Davis III
//Project: TRAC Ticket Manager v2
//Date: 14 Mar 2014

namespace TRACv2.UI
{
    public partial class FormMain : Form
    {
        #region [ Fields ]

        private readonly TRACFacade _controller;

        #endregion


        #region [ Constructor ]

        public FormMain(TRACFacade controller)
        {
            InitializeComponent();
            _controller = controller;
            PopulateDataGrid();
        }

        #endregion

        #region [ Control Events ]

        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void btnAddTicket_Click(object sender, EventArgs e)
        {
            using (var form = new FormAddTicket(_controller))
            {
                var result = form.ShowDialog();
                if (result == DialogResult.OK)
                {
                    PopulateDataGrid();
                }
            }
        }

        private void btnReport_Click(object sender, EventArgs e)
        {
            var form = new FormReports(_controller);
            form.ShowDialog();
        }

        #endregion

        #region [ Methods ]

        private void PopulateDataGrid()
        {
            dgvMain.Columns.Clear();
            var col = new DataGridViewButtonColumn();
            col.UseColumnTextForButtonValue = true;
            col.Name = "View Ticket";
            col.Text = "View Ticket";
            dgvMain.Columns.Add(col);
            dgvMain.DataSource = _controller.GetTicketTable(_controller.GetAllTickets(false));
        }

        #endregion

        private void dgvMain_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvMain.Columns[e.ColumnIndex].Name == "View Ticket")
            {
                int row = dgvMain.CurrentCell.RowIndex;
                string valueToPass = (dgvMain.Rows[row].Cells[2].Value.ToString().Trim());
                if (valueToPass != "")//make sure empty value is not passed to the database
                {
                    using (var form = new FormUpdateTicket(_controller, _controller.GetTicketByNumber(valueToPass)))
                    {
                        var result = form.ShowDialog();
                        if (result == DialogResult.OK)
                        {
                            PopulateDataGrid();
                        }
                    }
                }
                else
                    MessageBox.Show("Ticket Number Doesn't exist in the DataBase", "Ticket Doesn't Exist!");
            }
        }

        

    }
}
